<template>
    <el-container style="height: 100vh; justify-content: center; align-items: center;">
      <el-main>
        <el-card class="login-card" style="width: 400px; padding: 20px;">
          <div class="login-header">
            <h2>社区管理系统</h2>
          </div>
          <el-form :model="form" ref="loginForm" status-icon :rules="rules" label-width="100px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="form.password" placeholder="请输入密码" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleLogin" style="width: 100%;" :loading="loading">登录</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-main>
    </el-container>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import { ElContainer, ElMain, ElCard, ElForm, ElFormItem, ElInput, ElButton } from 'element-plus';
  import { useRouter } from 'vue-router';
  import { login } from '@/utils/axios'; // 假设有一个 login 函数封装在 axios 中
  
  const router = useRouter();
  const form = ref({
    username: '',
    password: ''
  });
  const loading = ref(false);
  
  const rules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符之间', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: 'blur' }
    ]
  };
  
  // 登录请求处理
  const handleLogin = async () => {
    try {
      await this.$refs.loginForm.validate();
      loading.value = true;
      const response = await login(form.value.username, form.value.password);
      localStorage.setItem('token', response.token); // 保存 token
      router.push('/home'); // 登录成功后跳转到首页
    } catch (error) {
      loading.value = false;
      console.error(error);
    }
  };
  </script>
  
  <style scoped>
  .login-card {
    max-width: 400px;
    margin: 0 auto;
  }
  
  .login-header {
    text-align: center;
    margin-bottom: 20px;
  }
  
  .el-form-item {
    margin-bottom: 15px;
  }
  </style>
  